package top.zhangjianyong.tools.service.api.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.zhangjianyong.tools.entity.User;
import top.zhangjianyong.tools.factory.UserFactory;
import top.zhangjianyong.tools.parm.UserLoginParm;
import top.zhangjianyong.tools.parm.UserRegParm;
import top.zhangjianyong.tools.service.api.UserService;
import top.zhangjianyong.tools.service.mybatis.IUserService;
import top.zhangjianyong.tools.utils.ApiResponse;
import top.zhangjianyong.tools.user.UserHolder;

/**
 * @author ： zhangjianyong
 * @date ： 2021/11/1 15:34
 */
@SuppressWarnings("rawtypes")
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private IUserService iUserService;

    @Override
    public ApiResponse login(UserLoginParm userLoginParm) throws Exception {

        User one = iUserService.lambdaQuery()
                .eq(User::getUsername, userLoginParm.getUsername())
                .eq(User::getPassword,  userLoginParm.getPassword())
                .one();
        if (one != null) {
            UserHolder.user(one);
            return ApiResponse.success(one);
        } else {
            return ApiResponse.fail("用户名或密码错误");
        }
    }

    @Transactional
    @Override
    public ApiResponse reg(UserRegParm userRegParm) throws Exception {
        User one = iUserService.lambdaQuery()
                .eq(User::getUsername, userRegParm.getUsername())
                .one();
        if (one != null)
            return ApiResponse.fail("用户名已存在");
        else {
            User user = UserFactory.create(userRegParm);
            iUserService.save(user);
            UserHolder.user(user);
            return ApiResponse.success();
        }
    }
}
